package csu.web.mypetstore.persistence.impl;

import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.persistence.CartDao;
import csu.web.mypetstore.persistence.DBUtil;
import csu.web.mypetstore.service.CatalogService;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class CartImpl implements CartDao {

    private static final String INSTERCARTITEM_TO_CART = "INSERT INTO " +
            "carts (userid,cartinfo)" +
            "VALUES (?,?)";


    @Override
    public void insertCart(String userid,Cart cart) {
        String itemId = "";
            try {
                String cartInfo = "";
                Connection connection = DBUtil.getConnection();
                PreparedStatement insertStatement = connection.prepareStatement(INSTERCARTITEM_TO_CART);
                insertStatement.setString(1, userid);
                for (CartItem cartitem : cart.getCartItemList()){
                    cartInfo+= cartitem.getItem().getItemId() + " " + String.valueOf(cartitem.getQuantity()) + " ";
                }
                    insertStatement.setString(2,cartInfo);
                insertStatement.executeUpdate();
                insertStatement.close();
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

    }

    @Override
    public void updateCart(String userid, Cart cart) {
        String cartInfo="";
        for (CartItem cartitem : cart.getCartItemList()){
            cartInfo+= cartitem.getItem().getItemId() + " " + String.valueOf(cartitem.getQuantity()) + " ";
        }
        String UPDATECARTINFO = "UPDATE carts " + "SET cartinfo = '" + cartInfo + "'" + " WHERE userid = '" + userid + "'";

        try{
            Connection connection = DBUtil.getConnection();
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(UPDATECARTINFO);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateCart(String userid, String itemID, String quantity) {
        String cartInfo="";


        try{
            Connection connection = DBUtil.getConnection();

            String sql = "SELECT cartinfo FROM carts WHERE userid = ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {

                statement.setString(1, userid);

                try (ResultSet resultSet = statement.executeQuery()) {

                    if (resultSet.next()) {
                        cartInfo = resultSet.getString("cartinfo");
                    }

                }
            }
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        String[] words = cartInfo.split("\\s+"); // 以空格分割字符串

        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(itemID) && i + 1 < words.length) {
                words[i + 1] = quantity; // 替换itemId后面的单词
                break;
            }
        }

        cartInfo = String.join(" ",words);

        String UPDATECARTINFO = "UPDATE carts " + "SET cartinfo = '" + cartInfo + "'" + " WHERE userid = '" + userid + "'";

        try{
            Connection connection = DBUtil.getConnection();
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(UPDATECARTINFO);
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public boolean checkCartByUserId(String userid) {
        boolean hasRecord = false;

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement()) {

            // 编写 SQL 查询语句
            String sql = "SELECT COUNT(*) FROM carts WHERE userid = '" + userid + "'";

            // 执行 SQL 查询语句
            try (ResultSet rs = stmt.executeQuery(sql)) {
                if (rs.next()) {
                    int count = rs.getInt(1);
                    // 如果查询结果大于0，表示有对应userid的记录
                    if (count > 0) {
                        hasRecord = true;
                    }
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return hasRecord;
    }

    @Override
    public Cart getCart(String userid) {
        String cartInfo = null;

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement()) {

            // 编写 SQL 查询语句
            String sql = "SELECT cartinfo FROM carts WHERE userid = '" + userid + "'";

            // 执行 SQL 查询语句
            try (ResultSet rs = stmt.executeQuery(sql)) {
                if (rs.next()) {
                    cartInfo = rs.getString("cartinfo");
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        if(cartInfo==null||cartInfo.equals(""))
        {
            return null;
        }else{
            String[] parts = cartInfo.split(" ");

            // 创建一个Map用于保存id和数量的对应关系
            Map<String, Integer> idQuantityMap = new HashMap<>();

            // 使用循环遍历分割后的字符串数组
            for (int i = 0; i < parts.length; i += 2) {
                String id = parts[i]; // 获取当前位置的id
                int quantity = Integer.parseInt(parts[i + 1]); // 获取当前位置的数量并转为整数

                // 将id和对应的数量保存到Map中
                idQuantityMap.put(id, quantity);
            }

            Cart cart  = new Cart();
            CatalogService catalogService = new CatalogService();

            for (Map.Entry<String, Integer> entry : idQuantityMap.entrySet()) {
                String id = entry.getKey();
                int quantity = entry.getValue();
                boolean isInStock = catalogService.isItemInStock(id);
                Item item = catalogService.getItem(id);
                cart.addItem(item, isInStock);
                cart.setQuantityByItemId(id,quantity);
            }
            return cart;
        }

    }
}
